package com.example.springaop.aop.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.dingtalk.api.request.OapiRobotSendRequest;
import com.dingtalk.open.app.api.open.http.HttpConstants;
import com.dingtalk.open.app.api.util.IoUtils;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class BotReplierRfx {
    private final String webhook;
    private final int timeout = 60000;

    public BotReplierRfx(String webhook) {
        this.webhook = webhook;
    }

    public static BotReplierRfx fromWebhook(String webhook) {
        return new BotReplierRfx(webhook);
    }

    public String replyText(String text) throws IOException {
        return replyText(text, null);
    }
    public String replyMarkdown(String title, String text) throws IOException {
        return replyMarkdown(title, text, null);
    }

    public String replyText(String text, List<String> atUserIds) throws IOException {
        final HttpURLConnection connection = getHttpURLConnection();

        Map<String, Object> textContent = new HashMap<>();
        textContent.put("content", text);
        Map<String, Object> request = new HashMap<>();
        request.put("msgtype", "text");
        request.put("text", textContent);
/*        request.put("msgtype", "link");
        request.put("link", " {\n" +
                "        \"text\": \"这个即将发布的新版本，创始人xx称它为红树林。而在此之前，每当面临重大升级，产品经理们都会取一个应景的代号，这一次，为什么是红树林\", \n" +
                "        \"title\": \"时代的火车向前开\", \n" +
                "        \"picUrl\": \"\", \n" +
                "        \"messageUrl\": \"https://www.dingtalk.com/s?__biz=MzA4NjMwMTA2Ng==&mid=2650316842&idx=1&sn=60da3ea2b29f1dcc43a7c8e4a7c97a16&scene=2&srcid=09189AnRJEdIiWVaKltFzNTw&from=timeline&isappinstalled=0&key=&ascene=2&uin=&devicetype=android-23&version=26031933&nettype=WIFI\"\n" +
                "    }");*/
/*        request.put("msgtype", "markdown");
        request.put("markdown", "{\n" +
                "         \"title\":\"杭州天气\",\n" +
                "         \"text\": \"#### 杭州天气 @150XXXXXXXX \\n > 9度，西北风1级，空气良89，相对温度73%\\n > ![screenshot](https://img.alicdn.com/tfs/TB1NwmBEL9TBuNjy1zbXXXpepXa-2400-1218.png)\\n > ###### 10点20分发布 [天气](https://www.dingtalk.com) \\n\"\n" +
                "     }");        */
        /*request.put("msgtype", "actionCard");
        request.put("actionCard", "{\n" +
                "        \"title\": \"乔布斯 20 年前想打造一间苹果咖啡厅，而它正是 Apple Store 的前身\", \n" +
                "        \"text\": \"![screenshot](https://gw.alicdn.com/tfs/TB1ut3xxbsrBKNjSZFpXXcXhFXa-846-786.png) \n" +
                " ### 乔布斯 20 年前想打造的苹果咖啡厅 \n" +
                " Apple Store 的设计正从原来满满的科技感走向生活化，而其生活化的走向其实可以追溯到 20 年前苹果一个建立咖啡馆的计划\", \n" +
                "        \"btnOrientation\": \"0\", \n" +
                "        \"singleTitle\" : \"阅读全文\",\n" +
                "        \"singleURL\" : \"https://www.dingtalk.com/\"\n" +
                "    }");

        request.put("msgtype", "actionCard");
        request.put("actionCard", "{\n" +
                "        \"title\": \"我 20 年前想打造一间苹果咖啡厅，而它正是 Apple Store 的前身\", \n" +
                "        \"text\": \"![screenshot](https://img.alicdn.com/tfs/TB1NwmBEL9TBuNjy1zbXXXpepXa-2400-1218.png) \\n\\n #### 乔布斯 20 年前想打造的苹果咖啡厅 \\n\\n Apple Store 的设计正从原来满满的科技感走向生活化，而其生活化的走向其实可以追溯到 20 年前苹果一个建立咖啡馆的计划\", \n" +
                "        \"btnOrientation\": \"0\", \n" +
                "        \"btns\": [\n" +
                "            {\n" +
                "                \"title\": \"内容不错\", \n" +
                "                \"actionURL\": \"https://www.dingtalk.com/\"\n" +
                "            }, \n" +
                "            {\n" +
                "                \"title\": \"不感兴趣\", \n" +
                "                \"actionURL\": \"https://www.dingtalk.com/\"\n" +
                "            }\n" +
                "        ]\n" +
                "    }");

        request.put("msgtype", "feedCard");
        request.put("feedCard", "{\n" +
                "        \"links\": [\n" +
                "            {\n" +
                "                \"title\": \"时代的火车向前开1\", \n" +
                "                \"messageURL\": \"https://www.dingtalk.com/\", \n" +
                "                \"picURL\": \"https://img.alicdn.com/tfs/TB1NwmBEL9TBuNjy1zbXXXpepXa-2400-1218.png\"\n" +
                "            },\n" +
                "            {\n" +
                "                \"title\": \"时代的火车向前开2\", \n" +
                "                \"messageURL\": \"https://www.dingtalk.com/\", \n" +
                "                \"picURL\": \"https://img.alicdn.com/tfs/TB1NwmBEL9TBuNjy1zbXXXpepXa-2400-1218.png\"\n" +
                "            }\n" +
                "        ]\n" +
                "    }");*/

        if (atUserIds != null && atUserIds.size() > 0) {
            Map<String, Object> atContent = new HashMap<>();
            atContent.put("atUserIds", atUserIds);
            request.put("at", atContent);
        }
        connection.getOutputStream().write(JSON.toJSONBytes(request, SerializerFeature.WriteEnumUsingToString));
        connection.getOutputStream().flush();
        if (connection.getResponseCode() == HttpConstants.STATUS_OK) {
            try {
                byte[] bytes = IoUtils.readAll(connection.getInputStream());
                return new String(bytes, StandardCharsets.UTF_8);
            } catch (Exception e) {
                throw new IOException(e.getMessage());
            }
        } else {
            try {
                byte[] bytes = IoUtils.readAll(connection.getErrorStream());
                throw new IOException(String.format("status=%s, msg=%s", connection.getResponseCode(), bytes != null ? new String(bytes) : ""));
            } catch (Exception e) {
                throw new IOException(e.getMessage());
            }
        }
    }


    public String replyMarkdown(String title1, String text1, List<String> atUserIds) throws IOException {
        final HttpURLConnection connection = getHttpURLConnection();
        Map<String, Object> markdownContent = new HashMap<>();
        markdownContent.put("title", title1);
        markdownContent.put("text", text1);
        Map<String, Object> request = new HashMap<>();
        request.put("msgtype", "markdown");
        request.put("markdown", markdownContent);
        if (atUserIds != null && atUserIds.size() > 0) {
            Map<String, Object> atContent = new HashMap<>();
            atContent.put("atUserIds", atUserIds);
            request.put("at", atContent);
        }

        /*OapiRobotSendRequest request = new OapiRobotSendRequest();
        request.setMsgtype("text");
        OapiRobotSendRequest.Text text = new OapiRobotSendRequest.Text();
        text.setContent(text1+"helle world");
        request.setText(text);
        OapiRobotSendRequest.At at = new OapiRobotSendRequest.At();
//        at.setAtMobiles(atUserIds);
//// isAtAll类型如果不为Boolean，请升级至最新SDK
        at.setIsAtAll(false);
        at.setAtUserIds(atUserIds);
        request.setAt(at);*/

        connection.getOutputStream().write(JSON.toJSONBytes(request, SerializerFeature.WriteEnumUsingToString));
        connection.getOutputStream().flush();
        if (connection.getResponseCode() == HttpConstants.STATUS_OK) {
            try {
                byte[] bytes = IoUtils.readAll(connection.getInputStream());
                return new String(bytes, StandardCharsets.UTF_8);
            } catch (Exception e) {
                throw new IOException(e.getMessage());
            }
        } else {
            try {
                byte[] bytes = IoUtils.readAll(connection.getErrorStream());
                throw new IOException(String.format("status=%s, msg=%s", connection.getResponseCode(), bytes != null ? new String(bytes) : ""));
            } catch (Exception e) {
                throw new IOException(e.getMessage());
            }
        }
    }

    private HttpURLConnection getHttpURLConnection() throws IOException {
        final HttpURLConnection connection = (HttpURLConnection) new URL(webhook).openConnection();
        connection.setRequestMethod(HttpConstants.METHOD_POST);
        connection.setReadTimeout(this.timeout);
        connection.setConnectTimeout(this.timeout);
        connection.setRequestProperty(HttpConstants.HEADER_CONTENT_TYPE, HttpConstants.CONTENT_TYPE_APPLICATION_JSON);
        connection.setRequestProperty(HttpConstants.HEADER_ACCEPT, "application/json");
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.connect();
        return connection;
    }
}
